package com.be.beadmin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.be.beadmin.service.entity.NotifyInfo;
import com.be.beadmin.service.repository.NotifyTemplateInfoRepository;
import com.be.beadmin.service.service.NotifyTemplateInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@ServerEndpoint(value = "/ws/imserver/{username}")
@Component
public class WebSocketNotifyService {

    private static final Logger log = LoggerFactory.getLogger(WebSocketNotifyService.class);

//    private static CopyOnWriteArraySet<WebSocketService> webSocketSet = new CopyOnWriteArraySet<WebSocketService>();
    /**
     * 记录当前在线连接数
     */
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();


    /**
     * 当前用户发送的离线消息 1.第一个收到消息的人 2.第二个是Map的String发送消息的人,Object是消息实体
     */
    private static final ConcurrentMap<String, Map<String, List<Object>>> messageMap=new ConcurrentHashMap<>();

    private static NotifyTemplateInfoService notifyTemplateInfoService;
//

    @Autowired
    public void setNotifyTemplateInfoService(NotifyTemplateInfoService notifyTemplateInfoService) {
        WebSocketNotifyService.notifyTemplateInfoService = notifyTemplateInfoService;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username){

        sessionMap.put(username, session);
        log.info("有新用户加入，username={}, 当前在线人数为：{}", username, sessionMap.size());

        // 循环发送,到当前登录用户
        //巡检任务提前7天发消息
        LocalDate currentDate = LocalDate.now();
        LocalDate newDate = currentDate.plusDays(7);
        // 将 LocalDate 转换为 Date
        Date date = Date.from(newDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

        notifyTemplateInfoService.generateNotifyTemplateInfoOfInspectTask(username,date);


        //获取未读消息
        Map<String, List<Object>> maps = notifyTemplateInfoService.findNotReadNotifyTemplateInfoOfUserName(username);
        if(maps!=null){

            List<Object> notifies = new ArrayList<>();
            //发给当前用户
            for (String key: maps.keySet()) {
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.set("from", key);  // from 是 zhang
//                jsonObject.set("text", lists.get(key));  // text 同上面的text

                notifies.addAll(maps.get(key));
//                for(Object notifyInfo:notifies){
//                    this.sendMessage((NotifyInfo) notifyInfo, session);
//                }

//                this.sendMessage(maps.get(key).toString(), session);

            }
            messageMap.put(username,maps);
            this.sendMessage(JSON.toJSONString(notifies), session);


//            messageMap.remove(username);
        }

    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("username") String username){
        sessionMap.remove(username);

        log.info("有一连接关闭，移除username={}的用户session, 当前在线人数为：{}", username, sessionMap.size());

        //清空消息队列
        messageMap.remove(username);

    }


    @OnError
    public void onError(Session session, Throwable error){
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 收到客户端消息后调用的方法
     * 后台收到客户端发送过来的消息
     * onMessage 是一个消息的中转站
     * 接受 浏览器端 socket.send 发送过来的 json数据
     * @param
     */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("username") String username){

    }

    //------------------------------------------------------------

    /**
     * 服务端发送消息给客户端
     */
    //private void sendMessage(NotifyInfo notifyInfo, Session toSession) {
    private void sendMessage(String message, Session toSession) {
        //String message = notifyInfo.getNotifyDesc();
        try {
            log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }

    /**
     * 服务端发送消息给所有客户端
     */
    private void sendMessageToAllUsers(NotifyInfo notifyInfo) {
        String message = notifyInfo.getNotifyDesc();
        try {
            for (Session session : sessionMap.values()) {
                log.info("服务端给客户端[{}]发送消息{}", session.getId(), message);
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }


    /**
     * 定义给某用户发送信息
     * @param notifyInfo 消息实体
     * @param receiverName 用户名
     */
    public void sendMessageToUser(NotifyInfo notifyInfo,String receiverName) {
        String message = notifyInfo.getNotifyDesc();
        // 发送给
        Session toSession = null; // 根据 to用户名来获取 session，再通过session发送消息文本
        if(sessionMap != null && sessionMap.size() > 0) {
            toSession = sessionMap.get(receiverName);
        }
        //接收人 在线，直接发送给他
        if (toSession != null) {
            Map<String, List<Object>> maps= new HashMap<>();

            if(messageMap.get(receiverName)!=null)maps= messageMap.get(receiverName);

            String senderName = notifyInfo.getSenderName();

            List<Object> notifyInfos =new ArrayList<>();
            if(maps.get(senderName)!=null) notifyInfos=maps.get(senderName);
            notifyInfos.add(notifyInfo);
            maps.put(senderName,notifyInfos);


            List<Object> notifies = new ArrayList<>();

            Map<String, List<Object> > lists= messageMap.get(receiverName);
            for (String key: lists.keySet()) {

                notifies.addAll(lists.get(key));
                //this.sendMessage(JSON.toJSONString(lists.get(key)), toSession);
            }

            messageMap.put(receiverName,maps);

            this.sendMessage(JSON.toJSONString(notifies), toSession);
//            this.sendMessage(JSON.toJSONString(notifyInfo), toSession);
            //this.sendMessage(notifyInfo, toSession);
            log.info("发送给用户username={}，消息：{}", receiverName, message);
        }else {

        }
    }

    /**
     * 消息管理页面更新已读状态后，更新铃铛
     * @param notifyInfoList 消息实体列表
     * @param receiverName 用户名
     */
    public void updateMessageToUser(List<NotifyInfo> notifyInfoList,String receiverName) {
        Session toSession = null; // 根据 to用户名来获取 session，再通过session发送消息文本
        if(sessionMap != null && sessionMap.size() > 0) {
            toSession = sessionMap.get(receiverName);
        }
        if(toSession!=null){
            Map<String, List<Object>> maps= new HashMap<>();
            if(messageMap.get(receiverName)!=null) maps= messageMap.get(receiverName);

            List<Object> newNotifyList =new ArrayList<>();
            for (String key: maps.keySet()) {
                List<Object> allNotifyInfoList = maps.get(key);
                allNotifyInfoList.removeAll(notifyInfoList);
                //this.sendMessage(JSON.toJSONString(lists.get(key)), toSession);
                maps.put(key,allNotifyInfoList);
                newNotifyList.addAll(allNotifyInfoList);
            }
            messageMap.put(receiverName,maps);
            this.sendMessage(JSON.toJSONString(newNotifyList), toSession);
        }else{
            //不在线不管
        }
    }

}
